#!/usr/bin/perl
# ups main page

require './ups-lib.pl';

&init_config();
&ReadParse();

#&header();

my $content = &read_ups_list();
my $driver;
my $newPort = "/dev/".$in{'port'};

foreach my $i (keys %$content)
{
	next if($i ne $in{'company'});
	foreach my $j (@{$content->{$i}})
	{
		$j =~ /(.+)=(.+)/;
		next if($1 ne $in{'model'});

		$driver = $2;
		last;
	}
}

my $conf = &get_ups_conf();

#foreach my $i (keys %$conf)
#{
#	print $i,"=",$conf->{$i};
#	print "<hr>";
#}

#print "driver:",$conf->{'driver'};
#print "<hr>";
#print "port:",$conf->{'port'};

if(($conf->{'driver'} eq $driver)&&($conf->{'port'} eq $newPort))
{
	&nas_syslog("UPS","naslog_warning",19006,"the ups configuration is identical to old one!");
	if($in{'upsstatus'} eq "disable")
	{
		`upsdrvctl start`;
		`upsd`;
		`upsmon 2>&1`;

	}
}
else
{
	&nas_syslog("UPS","naslog_info",19007,"the ups configuration is changed!");
	if($in{'upsstatus'} eq "enable")
	{
		`upsmon -c stop 2>&1`;

		`upsd -c stop`;

		`upsdrvctl stop`;

	}

	my $file = &read_file_lines($config{'upsconf'});
	for(my $i=0; $i<@$file; $i++)
	{
		next if($file->[$i] =~ /^#/);
		next if($file->[$i] =~ /^\s*$/);
		next if($file->[$i] =~ /\[ups\]/);
		my $olddriver = $conf->{'driver'};
		my $oldport = $conf->{'port'};
		$file->[$i] =~ s/$olddriver/$driver/;
		$file->[$i] =~ s/$oldport/$newPort/;
	}
	&flush_file_lines();

	`upsdrvctl start`;
	`upsd`;
	`upsmon 2>&1`;


}


#&footer();

&redirect("index.cgi");
